var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js');

/**
 * @description: 商品分类
 */
router.get('/api/goods/list', function(req, res, next) {
	res.send({
		"code": 200,
		"data": [{
			id: 1,
			name: "家居家纺",
			data: [{
					name: "家纺",
					list: [{
							id: 1,
							name: '毛巾',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 2,
							name: '浴巾',
							imgUrl: "../../static/1.jpg"
						}
					],
				},
				{
					name: "生活用品",
					list: [{
							id: 1,
							name: '垃圾袋',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 2,
							name: '香皂',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 3,
							name: '筷子',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 4,
							name: '彩板',
							imgUrl: "../../static/1.jpg"
						}
					],
				}
			],
		}, {
			id: 2,
			name: "女装",
			data: [{
					name: "裙装",
					list: [{
							id: 1,
							name: '长裙',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 2,
							name: '半身裙',
							imgUrl: "../../static/1.jpg"
						}
					],
				},
				{
					name: "上衣",
					list: [{
							id: 1,
							name: '夹克',
							imgUrl: "../../static/1.jpg"
						},
						{
							id: 2,
							name: '衬衫',
							imgUrl: "../../static/1.jpg"
						}
					],
				}
			],
		}]
	})
});

// 商品分类
router.get(`/api/category/list`, function(req, res, next) {
	connection.query(
		`SELECT c.id AS id,c.name AS name,JSON_ARRAYAGG(JSON_OBJECT
		('name', sc.name, 'list', p.products)) AS data FROM category c  INNER JOIN sub_category sc ON c.id = sc.category_id INNER JOIN 
		(SELECT sc.id AS subcategory_id, sc.name AS subcategory_name,JSON_ARRAYAGG(JSON_OBJECT
		('id', p.id, 'name', p.name, 'imgUrl', p.imgUrl)) AS products FROM sub_category sc INNER JOIN product p ON sc.id = p.subcategory_id GROUP BY sc.id, sc.name )
		 p ON sc.id = p.subcategory_id GROUP BY c.id, c.name`,
		function(error, results) {
			if (error) throw error
			res.send({
				data: {
					results
				}
			})
		})
})

module.exports = router;